﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model;
using Common;
using System.IO;
using System.Data;

namespace BLL
{
    public class FileBll
    {
        #region 构造函数



        #endregion

        #region 公共函数

        public List<ETL_Source_View_ColumnConfigInfo> GetTableColumnList(string filePath, string viewName, string textQualifier, string columnSeparator, string fileUserName, string filePassword)
        {
            var list = new List<ETL_Source_View_ColumnConfigInfo>();
            var streamResult = GetFileStream(filePath, viewName, fileUserName, filePassword, string.Empty);
            if (streamResult.Success == false)
            {
                //jsonResponse.Success = false;
                //jsonResponse.Message = streamResult.Message;
                //return Json(jsonResponse, "text/x-json");
                return list;
            }
            //System.IO.StreamReader streamReader = new System.IO.StreamReader(streamResult.Data, System.Text.Encoding.GetEncoding("gb2312"));

            using (CsvReader csv = new CsvReader(streamResult.Data, System.Text.Encoding.GetEncoding("gb2312"), true))
            {
                var columnList = csv.Headers;
                foreach (var columnName in columnList)
                {
                    var sourceViewColumn = new ETL_Source_View_ColumnConfigInfo();
                    sourceViewColumn.ColumnName = columnName;
                    sourceViewColumn.ColumnIsExtract = 1;
                    //if (connType == "3")
                    //    sourceViewColumn.ColumnType = "nvarchar(max)";
                    sourceViewColumn.ColumnIsPK = 0;
                    sourceViewColumn.ColumnIsOrder = 0;
                    list.Add(sourceViewColumn);
                }
            }

            //string headLine = streamReader.ReadLine();
            //if (textQualifier == "<无>" || string.IsNullOrEmpty(textQualifier))
            //{
            //    headLine = headLine.Replace(columnSeparator, "$");
            //}
            //else
            //{
            //    headLine = headLine.Replace(textQualifier + columnSeparator + textQualifier, "$").Replace(textQualifier, "");
            //}
            //var columnList = headLine.Split('$').ToList();
            //foreach (var columnName in columnList)
            //{
            //    var sourceViewColumn = new ETL_Source_View_ColumnConfigInfo();
            //    sourceViewColumn.ColumnName = columnName;
            //    sourceViewColumn.ColumnIsExtract = 1;
            //    //if (connType == "3")
            //    //    sourceViewColumn.ColumnType = "nvarchar(max)";
            //    sourceViewColumn.ColumnIsPK = 0;
            //    sourceViewColumn.ColumnIsOrder = 0;
            //    list.Add(sourceViewColumn);
            //}

            return list;
        }

        public List<ETL_Source_View_ColumnConfigInfo> GetColumnInfoByOutSystem(List<ETL_Source_View_ColumnConfigInfo> columnList)
        {
            int index = 1;
            foreach (var columnItem in columnList)
            {
                columnItem.ColumnOrderID = index++;
                columnItem.ColumnName = columnItem.ColumnName;
                columnItem.ColumnType = "nvarchar";
                columnItem.ColumnLength = 0;
                columnItem.ColumnPrecision = 0;
                columnItem.ColumnScale = 0;
                columnItem.ColumnIsNullable = 0;
            }
            return columnList;
        }

        public DataTable GetSourceTableData(string filePath, string viewName, string textQualifier, string columnSeparator, string fileUserName, string filePassword)
        {
            DataTable dt = new DataTable();

            var streamResult = GetFileStream(filePath, viewName, fileUserName, filePassword, string.Empty);
            if (streamResult.Success == false)
            {
                return dt;
            }
            using (CsvReader csv = new CsvReader(streamResult.Data, System.Text.Encoding.GetEncoding("gb2312"), true))
            {
                var columnList = csv.Headers;
                foreach (var columnName in columnList)
                {
                    dt.Columns.Add(new DataColumn(columnName));
                }
                int rowCount = 10;
                int rowIndex = 0;
                while (csv.ReadNextRecord() && rowIndex < rowCount)
                {
                    var dtRow = dt.NewRow();
                    foreach (var columnName in columnList)
                    {
                        dtRow[columnName] = csv[columnName];
                    }
                    dt.Rows.Add(dtRow);
                }
            }
            return dt;
        }
        #endregion

        #region 私有函数


        private JsonResponse<Stream> GetFileStream(string filePath, string includeFileName, string fileUserName, string filePassword, string existRegex)
        {
            JsonResponse<Stream> result = new JsonResponse<System.IO.Stream>();
            if (string.IsNullOrEmpty(fileUserName))
            {
                if (!Directory.Exists(filePath))
                {
                    result.Success = false;
                    result.Message = string.Format("目录 {0} 不存在", filePath);
                    return result;
                }
                var fileNames = Directory.GetFiles(filePath);
                Dictionary<string, string> fileDict = new Dictionary<string, string>();
                string[] extensions = new string[] { ".txt", ".csv" };
                foreach (string fullfileName in fileNames)
                {
                    var fileName = System.IO.Path.GetFileName(fullfileName);
                    fileName = System.Text.RegularExpressions.Regex.Replace(fileName, "_([0-9]{8})\\.", ".");
                    var fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName).ToUpper();
                    var extension = System.IO.Path.GetExtension(fullfileName);
                    if (extensions.Contains(extension, (t1, t2) =>
                    {
                        if (t1.Equals(t2, StringComparison.CurrentCultureIgnoreCase))
                            return true;
                        else
                            return false;
                    }))
                    {
                        if (fileNameWithoutExtension.Equals(System.IO.Path.GetFileNameWithoutExtension(includeFileName), StringComparison.CurrentCultureIgnoreCase))
                        {
                            Stream stream = System.IO.File.Open(fullfileName, System.IO.FileMode.Open);
                            if (stream.Length > 0)
                            {
                                result.Data = stream;
                                result.Message = fullfileName;
                                result.Success = true;
                                return result;
                            }
                        }
                    }
                    //if(string fileName)
                }
            }
            else
            {
                using (FileConnect fc = new FileConnect(filePath, fileUserName, filePassword))
                {
                    if (fc.IsConnectted)
                    {
                        if (!Directory.Exists(filePath))
                        {
                            result.Success = false;
                            result.Message = string.Format("目录 {0} 不存在", filePath);
                            return result;
                        }
                        var fileNames = Directory.GetFiles(filePath);
                        Dictionary<string, string> fileDict = new Dictionary<string, string>();
                        string[] extensions = new string[] { ".txt", ".csv" };
                        foreach (string fullfileName in fileNames)
                        {
                            var fileName = System.IO.Path.GetFileName(fullfileName);
                            fileName = System.Text.RegularExpressions.Regex.Replace(fileName, "_([0-9]{8})\\.", ".");
                            var fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName).ToUpper();
                            var extension = System.IO.Path.GetExtension(fullfileName);
                            if (extensions.Contains(extension, (t1, t2) =>
                            {
                                if (t1.Equals(t2, StringComparison.CurrentCultureIgnoreCase))
                                    return true;
                                else
                                    return false;
                            }))
                            {
                                if (fileNameWithoutExtension.Equals(System.IO.Path.GetFileNameWithoutExtension(includeFileName), StringComparison.CurrentCultureIgnoreCase))
                                {
                                    Stream stream = System.IO.File.Open(fullfileName, System.IO.FileMode.Open);
                                    if (stream.Length > 0)
                                    {
                                        result.Data = stream;
                                        result.Message = fullfileName;
                                        result.Success = true;
                                        return result;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            result.Success = false;
            result.Message = string.Format("没有找到 {0} 相关的文件", includeFileName);
            return result;
        }

        #endregion
    }
}
